#include "event.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void onRead(int fd, short events, void *args) {
    char buf[128];
    read(fd, buf, 128);
    write(fd, buf, sizeof(buf));
}

void onAccept(int fd, short events, void *args) {
    struct event_base *base = (struct event_base *)args;
    int connfd;
    struct sockaddr_in cliAddr;

    socklen_t size = sizeof(cliAddr);
    connfd = accept(fd, (struct sockaddr*)&cliAddr, &size);
    if (connfd < 0) {
        return;
    }

    struct event *ev = malloc(sizeof(struct event));
    event_set(ev, base, connfd, EV_READ, onRead, NULL);
    int r = event_add(ev);
    assert(r == 0);
}

int main(int argc, char **argv)
{
    int port = atoi(argv[1]);

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    bind(listenfd, (struct sockaddr *)&addr, sizeof(addr));
    listen(listenfd, 10);

    struct event_base *base = event_base_new();
    assert(base);

    struct event ev;
    event_set(&ev, base, listenfd, EV_READ, onAccept, base);
    event_add(&ev);

    event_base_loop(base);

    return 0;
}
